// my/my.js
import {
  RechargeModel
} from '../../../models/recharge'
import {
  PayModel
} from '../../../models/pay'
import {
  Format
} from '../../../utils/common'
import {
  AccountModel
} from '../../../models/account'
import {
  MyModel
} from '../../../models/my'
const myModel = new MyModel()
const accountmodel = new AccountModel()
const payModel = new PayModel()
const rechargeModel = new RechargeModel()
const app = getApp()
let last
const format = new Format()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    recharge: {phone: '', mobileValue: '', cardAsn: ''},
    tabs: [
      {
        title: '立即充值',
      },
      {
        title: '历史账单',
      }
    ],
    activeTab: 0,
    btnDisabled: true,
    inputDisabled: false, //选择油枪
    checkBox: true,
    modalOpened4: false,
    openTicketType: '',
    rechargeActive: '', //充值活动
    openIfmemberpop: false, // 是否显示选择会员状态弹窗
    showConsume: false, // 是否显示选择会员状态弹窗-是否显示一键加油或者直接战舰
    consumeTxt: '', // 会员状态弹窗文字
    openTipPop: false, // 是否显示弹窗
    TipTxt: '', // 弹窗内容
    tips: '', // 点击按钮方法
    balance: 0,
    href: '', // 跳转页面
    firstClick: true,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.href) {
      this.setData({
        'href': options.href,
      })
    }
    // this.setData({
    //   'options': JSON.stringify(options),
    // })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let  pat = /(\d{3})\d*(\d{4})/;
    this.setData({
      firstClick: true,
    })
    console.log(app.globalData.user)
    if (app.globalData.user && app.globalData.user.openId) {
      let res = app.globalData.user
      this.setData({
        inputDisabled: false,
        'recharge[phone]': res.phone,
        'recharge[mobileValue]': res.phone.replace(pat, '$1****$2'),
        'recharge[cardAsn]': res.cardAsn,
        openTicketType: res.openTicketType,
        activityStatus: res.activityStatus,
        openIfmemberpop: false
      });
      if (app.globalData.user.cardAsn) {
        this.loadMyAccount()
      }
      if (!this.data.rechargeActive) {
        this.getActiveParam()
      }
    } else {
      my.showLoading({
        content: '加载中',
      })
      app.myLogin().then(res => {
        console.log('myLogin' + JSON.stringify(res))
        
        console.log('data' + JSON.stringify(app.globalData.user) )
        if (res && res.cardAsn) {
            this.loadMyAccount()
            this.setData({
              inputDisabled: false,
              'recharge[phone]': res.phone,
              'recharge[mobileValue]': res.phone.replace(pat, '$1****$2'),
              'recharge[cardAsn]': res.cardAsn,
              openTicketType: res.openTicketType,
              activityStatus: res.activityStatus,
              openIfmemberpop: false
            });
            this.getActiveParam()
        } else {
          this.setData({
            inputDisabled: false,
            consumeTxt: '',
            showConsume: false,
            openIfmemberpop: true,
          })
        }
        setTimeout(() => {
          my.hideLoading();
        }, 1000);

      })
    }
  },
  handleTabClick({ index }) {
    this.setData({
      activeTab: index,
    });
  },
  handleTabChange({ index }) {
    this.setData({
      activeTab: index,
    });
  },
  changePayAmount(e) {
    const currentQuickIndex = e.currentTarget.dataset.index
    const currentPayInput = this.data.quickAmount[currentQuickIndex]
    this.setData({
      currentQuickIndex:currentQuickIndex,
      payAmountInput: currentPayInput.price + '',
      realAmount: format.amount(currentPayInput.price * 100),
      btnDisabled: false
    })
    // console.log(currentQuickIndex)
  },
  onInput(e) {
    last = e.timeStamp
    this.setData({
      currentQuickIndex: 12
    })
    var mesValue
    if (!(e.detail.value)) {
      this.setData({
        btnDisabled: true,
        payAmountInput: ''
      })
      return
    }
    console.log(e.detail.value)
    if ((e.detail.value).indexOf('.') != -1) {
      mesValue = e.detail.value.substring(0, e.detail.value.length - 1);
      return
    }
    mesValue = e.detail.value;
    if (!mesValue) {
      this.setData({
        btnDisabled: true
      })
    } else {
      this.setData({
        btnDisabled: false
      })
    }
    this.setData({
      payAmountInput: mesValue
    })
  },
  onChange(e) {
    console.log(e);
    this.setData({
      checkBox: e.detail.value,

    });
  },
  tip(e) {
    let vm = this
    if (!this.data.recharge.cardAsn) {
      this.setData({
        consumeTxt: '',
        showConsume: false,
        openIfmemberpop: true,
      })
      return
    }
    const page = e.currentTarget.dataset.url
    if (page =='/pages/order/myOrder/myOrder'){
      my.navigateTo({
        url: page + '?activeTab=1'
      })
    }
  },
  toPay() {
    // my.reLaunch({
    //   url: '/pages/recharge/rechargeResult/rechargeResult'
    // })
    // return
    let vm = this
    if (!this.data.recharge.cardAsn) {
      this.setData({
        consumeTxt: '',
        showConsume: false,
        openIfmemberpop: true,
      })
      return
    }
    if (this.data.activityStatus == 1) {
      this.setData({
        modalOpened4: true,
      })
      return
    }
    const d = this.data
    if ((parseInt(d.payAmountInput) + this.data.balance) > 5000) {
      my.showToast({
        type: 'none',
        content: '充值账户余额上限为5000元,请修改你的充值金额',
        duration: 2000,
      });
      return
    }
    if (d.payAmountInput < 500) {
      my.showToast({
        type: 'none',
        content: '活动期间，充值金额500元起',
        duration: 2000,
      });
      return
    }
    if (this.data.firstClick) {
      this.setData({
        firstClick: false,
      })
    } else {
      return
    }
    const amount = (d.payAmountInput * 100).toFixed(0)
    const realAmount = format.amountClear(d.payAmountInput)
    console.log(this.data)
    if (!app.globalData.station || !app.globalData.station.alipay_store_id) {
      var store_id = app.globalData.mainStore
    } else {
      var store_id = app.globalData.station.alipay_store_id
    }
    payModel.recharge(amount, realAmount.toFixed(0), d.recharge.phone, store_id).then(res => {
      console.log(res)
      if (res && res.tradeNo) {
        vm.data.firstClick = true
        payModel.myPay('recharge',res.tradeNo, realAmount,this.data.href,res.orderId)
      } else {
        if (res && res.desc ) {
          this.setData({
            openTipPop: true,
            TipTxt: res.desc,
            tips: 'close',
          });
        } else {
          this.setData({
            openTipPop: true,
            TipTxt: '充值失败',
            tips: 'close',
          });
        }
      }
    });
  },
  getCouponListByOrderId() {
    let vm = this
    rechargeModel.getCouponListByOrderId().then(res => {
      if (res.activeName || res.src) {
        vm.setData({
          Registeractive: res,
        });
        vm.setData({
          openPop: true,
        })
        
      }
      console.log(res)
    })
  },
  onCounterPlusOne() {
    this.setData({
      openPop: false,
      // modalOpened4: true,
    })
    // app.globalData.ifSetPaw = 0
  },
  // 获取账户信息
  loadMyAccount() {
    myModel.loadMyAccount().then(res => {
      console.log(res)
      if (res) {
        if (res.code == '00') {
          this.setData({
            balance: res.result.balance
          })
        } else if (res.message) {
          this.setData({
            openTipPop: true,
            TipTxt: res.message,
            tips: 'close',
          });
        }
      } else {
        this.setData({
          openTipPop: true,
          TipTxt: '获取账户信息失败',
          tips: 'close',
        });
      }
      
    })
  },
  onModalClick21() {
    this.setData({
      modalOpened4: false,
    });
    my.navigateTo({
      url: '/pages/account/setPaw/setPaw'
    })
  },
  onModalClose21() {
    this.setData({
      modalOpened4: false,
    });
    // my.reLaunch({
    //   url: '/pages/my/my'
    // })
    // my.navigateBack()
    
  },
  checkOriginPwd() {
    accountmodel.checkOriginPwd().then(res => {
        console.log(res)
        if (res && res.code == '00') {
          this.setData({
            openTicketType: res.openTicketType
          });
          if (res.pinStatus == 0) {
            this.setData({
              // modalOpened4: true,
              openTicketType: res.openTicketType

            });
            app.globalData.ifSetPaw = 0
          } else {
            app.globalData.ifSetPaw = 1
            this.getActiveParam()
          }
        } else {
          my.showToast({
            type: 'none',
            content: '接口错误',
            duration: 1000,
          });
        }
      })
  },


  // 获取充值活动
  getActiveParam() {
    let vm = this
    rechargeModel.getActiveParam('actice').then(res => {
      console.log(res)
      if (res) {
        if (res.rechargeParam) {
          this.setData({
            'quickAmount': res.rechargeParam
          })
        }
        if (res.active && res.activeDetail) {
          this.setData({
            'rechargeActive[name]': res.active.bigSlogan,
            'rechargeActive[mallSlogan]': res.active.mallSlogan,
            'rechargeActive[activeDetail]': res.activeDetail
          })
        }
      } else {
        my.showToast({
          type: 'none',
          content: '获取充值活动失败',
          duration: 1000,
        });
      }
    })
  },
  toPage(e) {
    if (this.data.firstClick) {
      this.setData({
        firstClick: false,
      })
    } else {
      return
    }
    const page = e.currentTarget.dataset.url
    if (page == '/pages/recharge/rechargeActive/rechargeActive') {
      if (this.data.rechargeActive && this.data.mallSlogan) {
        my.navigateTo({
          url: page + '?activeDetail=' + encodeURIComponent(JSON.stringify(this.data.rechargeActive.activeDetail)),
        })
      } else {
        this.data.firstClick = true
      }
     
    } else {
      my.navigateTo({
        url: page
      })
    }
  },
  // 关掉弹窗
  onClose() {
    this.setData({
      firstClick: true,
      openIfmemberpop: false,
    });
  },
  // 点击知道了
  tipPopSure(tips) {
    this.setData({
      firstClick: true,
      openTipPop: false,
    });
    if (tips == 'href') {
      my.navigateBack('1')
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})